from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.contrib.auth.models import User
from django.conf import settings
import os
import uuid
from .models import KnowledgeDocument, InterviewSession, InterviewQuestion, InterviewAnswer
from .serializers import (
    KnowledgeDocumentSerializer, InterviewSessionSerializer, 
    InterviewQuestionSerializer, InterviewAnswerSerializer,
    FileUploadSerializer, AnswerSubmissionSerializer, SessionCreateSerializer
)
from .rag_service import ChromaRAGService

# 初始化RAG服务
rag_service = ChromaRAGService()

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_document(request):
    """上传文档到知识库"""
    serializer = FileUploadSerializer(data=request.data)
    if serializer.is_valid():
        uploaded_file = serializer.validated_data['file']
        title = serializer.validated_data.get('title', uploaded_file.name)
        
        # 保存文件
        file_path = os.path.join(settings.MEDIA_ROOT, 'knowledge_docs', uploaded_file.name)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        
        with open(file_path, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
        
        # 生成文档ID
        document_id = str(uuid.uuid4())
        
        # 添加到向量数据库
        result = rag_service.add_document(file_path, title, document_id)
        
        if result['success']:
            # 保存到数据库
            document = KnowledgeDocument.objects.create(
                id=document_id,
                title=title,
                content="",  # 内容存储在向量数据库中
                file_path=file_path,
                file_type=uploaded_file.content_type,
                vector_id=document_id
            )
            
            return Response({
                'success': True,
                'message': '文档上传成功',
                'document': KnowledgeDocumentSerializer(document).data
            }, status=status.HTTP_201_CREATED)
        else:
            return Response({
                'success': False,
                'message': f'文档处理失败: {result["error"]}'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def list_documents(request):
    """获取知识库文档列表"""
    documents = KnowledgeDocument.objects.all()
    serializer = KnowledgeDocumentSerializer(documents, many=True)
    return Response({
        'success': True,
        'documents': serializer.data
    })

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_session(request):
    """创建面试会话"""
    serializer = SessionCreateSerializer(data=request.data)
    if serializer.is_valid():
        session_name = serializer.validated_data['session_name']
        document_ids = serializer.validated_data.get('document_ids', [])
        
        # 创建会话
        session = InterviewSession.objects.create(
            user=request.user,
            session_name=session_name
        )
        
        # 关联文档
        if document_ids:
            documents = KnowledgeDocument.objects.filter(id__in=document_ids)
            session.knowledge_documents.set(documents)
        
        return Response({
            'success': True,
            'message': '面试会话创建成功',
            'session': InterviewSessionSerializer(session).data
        }, status=status.HTTP_201_CREATED)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def list_sessions(request):
    """获取用户的面试会话列表"""
    sessions = InterviewSession.objects.filter(user=request.user)
    serializer = InterviewSessionSerializer(sessions, many=True)
    return Response({
        'success': True,
        'sessions': serializer.data
    })

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_session_questions(request, session_id):
    """获取面试会话的问题"""
    try:
        session = InterviewSession.objects.get(id=session_id, user=request.user)
        
        # 检查是否已有问题
        existing_questions = InterviewQuestion.objects.filter(session=session)
        
        if not existing_questions.exists():
            # 生成问题
            questions = []
            for doc in session.knowledge_documents.all():
                # 从向量数据库获取文档内容
                similar_docs = rag_service.search_similar(doc.title, n_results=1)
                if similar_docs:
                    doc_questions = rag_service.generate_questions(similar_docs[0]['content'], num_questions=3)
                    for i, question_text in enumerate(doc_questions):
                        question = InterviewQuestion.objects.create(
                            session=session,
                            question_text=question_text,
                            question_type='technical',
                            source_document=doc,
                            order=len(questions) + i
                        )
                        questions.append(question)
            
            # 如果没有文档，生成通用问题
            if not questions:
                general_questions = [
                    "请介绍一下你的技术背景和经验。",
                    "你如何处理项目中的技术难题？",
                    "请描述一个你参与过的复杂项目。",
                    "你如何保持技术学习的更新？",
                    "请谈谈你对团队协作的理解。"
                ]
                
                for i, question_text in enumerate(general_questions):
                    question = InterviewQuestion.objects.create(
                        session=session,
                        question_text=question_text,
                        question_type='general',
                        order=i
                    )
                    questions.append(question)
        else:
            questions = list(existing_questions)
        
        serializer = InterviewQuestionSerializer(questions, many=True)
        return Response({
            'success': True,
            'questions': serializer.data
        })
        
    except InterviewSession.DoesNotExist:
        return Response({
            'success': False,
            'message': '面试会话不存在'
        }, status=status.HTTP_404_NOT_FOUND)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_answer(request):
    """提交答案并获取评估"""
    serializer = AnswerSubmissionSerializer(data=request.data)
    if serializer.is_valid():
        answer_text = serializer.validated_data['answer_text']
        question_id = serializer.validated_data['question_id']
        
        try:
            question = InterviewQuestion.objects.get(id=question_id)
            
            # 获取参考内容
            reference_content = ""
            if question.source_document:
                similar_docs = rag_service.search_similar(question.question_text, n_results=1)
                if similar_docs:
                    reference_content = similar_docs[0]['content']
            
            # 评估答案
            evaluation = rag_service.evaluate_answer(answer_text, question.question_text, reference_content)
            
            # 保存答案
            answer = InterviewAnswer.objects.create(
                question=question,
                answer_text=answer_text,
                similarity_score=evaluation['similarity_score'],
                quality_score=evaluation['quality_score'],
                feedback=evaluation['feedback']
            )
            
            return Response({
                'success': True,
                'message': '答案提交成功',
                'evaluation': {
                    'similarity_score': evaluation['similarity_score'],
                    'quality_score': evaluation['quality_score'],
                    'overall_score': evaluation['overall_score'],
                    'feedback': evaluation['feedback']
                },
                'answer': InterviewAnswerSerializer(answer).data
            })
            
        except InterviewQuestion.DoesNotExist:
            return Response({
                'success': False,
                'message': '问题不存在'
            }, status=status.HTTP_404_NOT_FOUND)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_session_results(request, session_id):
    """获取面试会话结果"""
    try:
        session = InterviewSession.objects.get(id=session_id, user=request.user)
        questions = InterviewQuestion.objects.filter(session=session)
        
        results = []
        total_score = 0
        question_count = 0
        
        for question in questions:
            try:
                answer = InterviewAnswer.objects.get(question=question)
                score = (answer.similarity_score + answer.quality_score) / 2
                total_score += score
                question_count += 1
                
                results.append({
                    'question': InterviewQuestionSerializer(question).data,
                    'answer': InterviewAnswerSerializer(answer).data,
                    'score': score
                })
            except InterviewAnswer.DoesNotExist:
                results.append({
                    'question': InterviewQuestionSerializer(question).data,
                    'answer': None,
                    'score': 0
                })
        
        # 计算平均分
        average_score = total_score / question_count if question_count > 0 else 0
        
        # 更新会话总分
        session.total_score = average_score
        session.status = 'completed'
        session.save()
        
        return Response({
            'success': True,
            'session': InterviewSessionSerializer(session).data,
            'results': results,
            'average_score': average_score,
            'total_questions': question_count
        })
        
    except InterviewSession.DoesNotExist:
        return Response({
            'success': False,
            'message': '面试会话不存在'
        }, status=status.HTTP_404_NOT_FOUND)

@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_document(request, document_id):
    """删除知识库文档"""
    try:
        document = KnowledgeDocument.objects.get(id=document_id)
        
        # 从向量数据库删除
        rag_service.delete_document(str(document_id))
        
        # 删除文件
        if os.path.exists(document.file_path):
            os.remove(document.file_path)
        
        # 删除数据库记录
        document.delete()
        
        return Response({
            'success': True,
            'message': '文档删除成功'
        })
        
    except KnowledgeDocument.DoesNotExist:
        return Response({
            'success': False,
            'message': '文档不存在'
        }, status=status.HTTP_404_NOT_FOUND)